import xml.etree.ElementTree as ET
# import xml.etree.ElementTree as etree
import os
from lxml import etree
from collections import OrderedDict

# Make sorted() a no-op for the ElementTree module
ET.sorted = lambda x: x

try:
    # python3 use a cPython implementation by default, prevent that
    ET.Element = ET._Element_Py


    # similarly, override SubElement method if desired
    def SubElement(parent, tag, attrib=OrderedDict(), **extra):
        attrib = attrib.copy()
        attrib.update(extra)
        element = parent.makeelement(tag, attrib)
        parent.append(element)
        return element


    ET.SubElement = SubElement
except AttributeError:
    pass  # nothing else for python2, ElementTree is pure python


def get_script_dir():
    return os.path.abspath(os.path.dirname(__file__))


def debug_element(el):
    print(el)
    print(type(el))


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False


def modify_row(row, rate):
    for attr_name in row.attrib:
        # 这里你把所有需要改的属性名称加上，只需要包含部分文字即可
        if '最' in attr_name or \
                '增加' in attr_name or \
                '技能ID' in attr_name:
            old_val = row.attrib[attr_name]
            if is_number(old_val):
                row.attrib[attr_name] = str(float(old_val) * rate)


def read_then_write(src_file, rate):
    if 'replaced' in src_file:
        return
    src_file = os.path.join(get_script_dir(), src_file)
    des_file = src_file.replace('.xml', '.replaced.xml')
    print(f'正在处理{src_file}')
    # debug_element(el_tree)
    xmlp = etree.XMLParser(encoding="utf-8", recover=True)
    el_tree = ET.parse(src_file, parser=xmlp)
    rows = el_tree.findall('row')
    for row in rows:
        modify_row(row, rate)
    el_tree.write(des_file, encoding='utf-8', xml_declaration=True)
    print(f'输出到{des_file}')


if __name__ == '__main__':
    for fn in os.listdir(os.getcwd()):
        if os.path.isfile(fn) and fn.endswith('.xml'):
            # 这里2.0随便改成别的数字
            read_then_write(fn, 2.0)
    print('结束')
